using System;
using System.Collections.Generic;
using Admin3000.Backend.Api.Entity;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using Admin3000.Backend.Api.ParamModel;
using Newtonsoft.Json;
using Admin3000.Backend.Api.Repository;
using Admin3000.Backend.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;

namespace Admin3000.Backend.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IRepository<Users> _usersRespository;
        private TokenParameter _tokenParameter;
        private readonly IConfiguration _configuration;

        public UsersController(IConfiguration configuration, IRepository<Users> usersRespository)
        {
            _configuration = configuration;
            _usersRespository = usersRespository;
            _tokenParameter = _configuration.GetSection("TokenParameter").Get<TokenParameter>();
        }

        [HttpGet]
        public dynamic Get([FromQuery]Pager pager)
        {
            // db.Users.up
            //不知道为啥写了这个就可以一页只显示10行
            //get请求默认从uri获取参数，所以这里加上FromQuery的特性才能正确获得参数
            var pageIndex=pager.PageIndex;
            var pageSize=pager.PageSize;

            //获得所有满足条件的记录
            var users = _usersRespository.Table.Where(x=>x.IsDeleted==false);
            
            //对获得的记录分页
            var u=users.Skip((pageIndex-1)*pageSize).Take(pageSize).ToList();
            
            //返回的数据里，带有数据和分页信息
            var res = new
            {
                Code = 1000,
                Data = new {Data =u,Pager =new {pageIndex,pageSize,rowsTotal=users.Count()}},
                Msg = "获取用户列表成功^_^"
            };
            return res;
        }

        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var user = _usersRespository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 1000,
                    Data = "",
                    Msg = "指定用户不存在"
                };

            }
            return new
            {
                Code = 1000,
                Data = user,
                Msg = "获取用户列表成功^_^"
            };

        }

        [HttpPost]
        public string Post(NewUser model)
        {
            // JsonSerializerSettings settings = new JsonSerializerSettings();
            // // settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            // settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            var username=model.Username.Trim();
            var password=model.Password.Trim();
            var remarks=model.Remarks;

            if(string.IsNullOrEmpty(username)){
               var tmp = new
            {
                Code = 1004,
                Data = "",
                Msg = "用户名不能为空，请确认后重试"
            };
            return JsonHelper.Serialize(tmp);
            }

            var user = new Users
            {
                Username = username,
                Password = password,
                Remarks=remarks
            };

            _usersRespository.Insert(user);

            var res = new
            {
                Code = 1000,
                Data = user,
                Msg = "创建用户成功"
            };
            return JsonHelper.Serialize(res);
        }



        // 根据id修改用户信息
        [HttpPut("{id}")]
        public dynamic Put(int id, NewUser model)
        {
            var user = _usersRespository.GetById(id);

            if (user != null)
            {
                user.Username = model.Username;
                //user.Password = model.Password;
                user.Remarks = model.Remarks;
                user.UpdatedTime = DateTime.Now;
                _usersRespository.Update(user);
                return JsonHelper.Serialize(new
                {
                    Code = 1000,
                    Data = user,
                    Msg = string.Format("你修改的用户的id为：{0}，已经修改成功，请注意查收", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 104,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                });
            }
        }


        // 根据Id删除用户
        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            var user = _usersRespository.GetById(id);   //数据库的更新传给user
            if (user != null)
            {
                user.IsDeleted = true;  //假删除 在页面不显示 在数据库显示
                _usersRespository.Update(user);
                return new
                {
                    Code = 1000,
                    Data = user,    //把user传给前端的data
                    Msg = string.Format("删除指定id为{0}的用户成功", id)
                };
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                };
            }

        }

         [HttpPost,Route("login")]
        public string Login(NewUser model)
        {
            var username=model.Username.Trim();
            var password=model.Password.Trim();

            var user=_usersRespository.Table.Where(x=>x.Username==username && x.Password==password).FirstOrDefault();
            dynamic res;
            if(user==null){
                 res = new{
                    Code = 1004,
                    Data = "",
                    Msg = "用户名不能为空或者密码不匹配，请确认后重试"    
                };
                
            }else{
                res=new{
                    Code = 1004,
                    Data = "",
                    Msg = "用户名不能为空，请确认后重试"
                };
            };
            return JsonHelper.Serialize(res);     
        }


        

        [AllowAnonymous]
        [HttpPost, Route("token")]
        public dynamic GetToken(NewUser model)
        {
            var username = model.Username.Trim();
            var password = model.Password.Trim();

            var user = _usersRespository.Table.Where(x => x.Username == username && x.Password == password).FirstOrDefault();

            if (user == null)
            {
                return new
                {
                    Code = 1001,
                    Data = user,
                    Msg = "用户名或密码不正确，请核对后重试"
                };
            }

            var token = TokenHelper.GenerateToekn(_tokenParameter, user);
            var refreshToken = "123456";

            var res = new
            {
                Code = 1000,
                Data = new { Token = token, RefreshToken = refreshToken },
                Msg = "用户登录成功，获取token成功"
            };
            return res;
        }
    }
}
